package com.galeno.day09.test;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.ArrayList;

/**
 * @author galeno
 * @Title:
 * @Description:
 * @date 2021/10/2621:15
 */
public class EventTimeTimer {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 12345);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);
        DataStreamSource<String> lines = env.socketTextStream("192.168.77.3", 9999);
        //1000,spark,1

        SingleOutputStreamOperator<String> timestampsAndWatermarks = lines.assignTimestampsAndWatermarks(WatermarkStrategy
                .<String>forBoundedOutOfOrderness(Duration.ZERO)
                .withTimestampAssigner(new SerializableTimestampAssigner<String>() {
                    @Override
                    public long extractTimestamp(String element, long recordTimestamp) {
                        recordTimestamp = Long.parseLong(element.split(",")[0]);
                        return recordTimestamp;
                    }
                }));
        SingleOutputStreamOperator<Tuple2<String, Integer>> tpMap = timestampsAndWatermarks.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                String[] split = value.split(",");
                return Tuple2.of(split[1], Integer.parseInt(split[2]));
            }
        });
        //先keyby在使用定时器
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = tpMap.keyBy(x -> x.f0);

        SingleOutputStreamOperator<Tuple2<String, Integer>> process = keyedStream.process(new KeyedProcessFunction<String, Tuple2<String, Integer>, Tuple2<String, Integer>>() {
            private transient ValueState<ArrayList<Tuple2<String, Integer>>> listValueState;
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<ArrayList<Tuple2<String, Integer>>> listValueStateDescriptor = new ValueStateDescriptor<ArrayList<Tuple2<String, Integer>>>("list-state", TypeInformation.of(new TypeHint<ArrayList<Tuple2<String, Integer>>>() {
                }));
                listValueState = getRuntimeContext().getState(listValueStateDescriptor);


            }

            @Override
            public void processElement(Tuple2<String, Integer> value, Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                /**
                 * processElement中不输出数据,而是将数据攒起来,然后注册定时器
                 */
                ArrayList<Tuple2<String, Integer>> tuple2ArrayList = listValueState.value();
                if (tuple2ArrayList == null) {
                    tuple2ArrayList = new ArrayList<>();
                }
                tuple2ArrayList.add(value);
                listValueState.update(tuple2ArrayList);

                //11:29:15 下一次触发的时间11：30：00
                //11:29:18 下一次触发的时间11：30：00
                long currentWatermark = ctx.timerService().currentWatermark();
                long triggerTime = (currentWatermark - currentWatermark % 60000) + 60000;
                System.out.println(ctx.getCurrentKey() + "注册定时器的waterMark" + sdf.format(currentWatermark)
                        + "定时器触发时间" + sdf.format(triggerTime)
                );


            }

            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                System.out.println("已经触发时间为" + sdf.format(timestamp));
                ArrayList<Tuple2<String, Integer>> tuple2ArrayList = listValueState.value();
                for (Tuple2<String, Integer> stringIntegerTuple2 : tuple2ArrayList) {

                    out.collect(stringIntegerTuple2);
                }

                tuple2ArrayList.clear();


            }
        });
        process.print();
        env.execute();


    }
}
